<template>
  <el-card>
    <h2>门店审核 - 图片上传</h2>
    <div v-if="store">
      <div style="margin-bottom:16px;">
        <b>门店名称：</b>{{ store.storeName }}<br />
        <!-- <b>门店ID：</b>{{ store.storeId }}<br /> -->
        <!-- <b>提交人：</b>{{ userStore.username }}（ID: {{ userStore.userId }}） -->
        <b>提交人：</b>{{ userStore.username }}
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="菜单图片" prop="menuImageArr">
          <UploadImage v-model="form.menuImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
        </el-form-item>
        <el-form-item label="装修图片" prop="decorationImageArr">
          <UploadImage v-model="form.decorationImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
        </el-form-item>
        <el-form-item label="活动图片" prop="activityImageArr">
          <UploadImage v-model="form.activityImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
        </el-form-item>
        <el-form-item label="基础配置图片" prop="configImageArr">
          <UploadImage v-model="form.configImageArr" :limit="1" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
        </el-form-item>
        <el-form-item label="下一位操作者" prop="nextOperatorName">
          <el-select v-model="form.nextOperatorName" placeholder="请选择下一位操作者">
            <el-option v-for="item in employee2List" :key="item.employeeId" :label="item.name" :value="item.account" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="onSubmit"
            :loading="isSubmitting"
            :disabled="isSubmitting"
          >
            {{ isSubmitting ? '提交中...' : '提交审核' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else>加载中...</div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import UploadImage from '@/components/UploadImage.vue';
import { useUserStore } from '@/store/user';

const route = useRoute();
const router = useRouter();
const store = ref(null);
const formRef = ref();
const form = ref({
  menuImageArr: [],
  decorationImageArr: [],
  activityImageArr: [],
  configImageArr: [],
  nextOperatorName: '',
});
const rules = {
  menuImageArr: [{ required: true, type: 'array', min: 1, message: '请上传菜单图片' }],
  decorationImageArr: [{ required: true, type: 'array', min: 1, message: '请上传装修图片' }],
  activityImageArr: [{ required: true, type: 'array', min: 1, message: '请上传活动图片' }],
  configImageArr: [{ required: true, type: 'array', min: 1, message: '请上传基础配置图片' }],
  nextOperatorName: [{ required: true, message: '请选择下一位操作者' }],
};
const employee2List = ref([]);
const userStore = useUserStore();
const isSubmitting = ref(false);

async function fetchStore() {
  // 调用后端接口 /api/store/detail/{storeId}
  const res = await fetch(`http://121.43.176.9:8090/api/store/detail/${route.params.storeId}`).then(r => r.json());
  if (res.code === 200) store.value = res.data;
}

async function fetchEmployee2List() {
  const res = await fetch('http://121.43.176.9:8090/api/employee/type2/list').then(r => r.json());
  if (res.code === 200) {
    employee2List.value = res.data;
  } else {
    employee2List.value = [];
  }
}

async function fetchEmployee1Photos() {
  const res = await fetch(`http://121.43.176.9:8090/api/employee/type1/photos?storeId=${route.params.storeId}`).then(r => r.json());
  if (res.code === 200 && res.data) {
    // 过滤掉 blob URL，只保留有效的图片URL
    const isValidUrl = (url) => {
      return url && !url.startsWith('blob:') && (url.startsWith('http://') || url.startsWith('https://'));
    };
    
    // 只更新图片相关的字段，不影响其他字段
    if (res.data.menuImage && isValidUrl(res.data.menuImage)) {
      form.value.menuImageArr = [{ url: res.data.menuImage }];
    }
    if (res.data.decorationImage && isValidUrl(res.data.decorationImage)) {
      form.value.decorationImageArr = [{ url: res.data.decorationImage }];
    }
    if (res.data.activityImage && isValidUrl(res.data.activityImage)) {
      form.value.activityImageArr = [{ url: res.data.activityImage }];
    }
    if (res.data.configImage && isValidUrl(res.data.configImage)) {
      form.value.configImageArr = [{ url: res.data.configImage }];
    }
  }
}

function isAllImagesUploaded() {
  // 检查每个图片数组，是否都至少有一个 http(s) 地址，且没有 loading 状态
  const arrs = [
    form.value.menuImageArr,
    form.value.decorationImageArr,
    form.value.activityImageArr,
    form.value.configImageArr
  ];
  for (const arr of arrs) {
    if (
      !arr ||
      arr.length === 0 ||
      arr.some(f => f.status === 'uploading' || f.status === 'ready') || // 还在上传
      !arr.some(f => f.url && (f.url.startsWith('http://') || f.url.startsWith('https://')))
    ) {
      return false;
    }
  }
  return true;
}

async function onSubmit() {
  if (isSubmitting.value) {
    return;
  }

  // 新增：图片上传状态校验
  if (!isAllImagesUploaded()) {
    ElMessage.error('请等待所有图片上传完成后再提交');
    return;
  }

  try {
    await formRef.value.validate();
  } catch (err) {
    const firstError = Object.values(err)[0]?.[0]?.message;
    if (firstError) {
      ElMessage.error(firstError);
    }
    return;
  }
  
  isSubmitting.value = true;
  
  const dto = {
    employeeId: userStore.userId,
    storeId: route.params.storeId,
    menuImage: form.value.menuImageArr[0]?.url || '',
    decorationImage: form.value.decorationImageArr[0]?.url || '',
    activityImage: form.value.activityImageArr[0]?.url || '',
    configImage: form.value.configImageArr[0]?.url || '',
    nextOperatorAccount: form.value.nextOperatorName, // 改为传递account
  };
  
  try {
    const res = await fetch('http://121.43.176.9:8090/api/employee/type1/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(dto),
    }).then(r => r.json());
    
    if (res.code === 200) {
      ElMessage.success('提交成功');
      setTimeout(() => {
        router.push('/employee/type1');
      }, 300);
    } else {
      ElMessage.error(res.msg || '提交失败');
    }
  } catch (e) {
    ElMessage.error('提交失败');
  } finally {
    isSubmitting.value = false;
  }
}

onMounted(async () => {
  try {
    // 先获取门店信息
    await fetchStore();
    // 再获取员工列表
    await fetchEmployee2List();
    // 最后获取员工1图片（如果是编辑模式）
    if (route.query.edit === '1') {
      await fetchEmployee1Photos();
    }
  } catch (error) {
    console.error('初始化失败:', error);
  }
});
</script> 